package it.orma.iridehr.validators;

import it.orma.iridehr.controllers.form.candidato.DocumentiForm;
import it.orma.iridehr.entities.SchedaCandidato;
import it.orma.iridehr.repository.RicercaRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.binding.validation.ValidationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.webflow.execution.RequestContext;
import org.springframework.webflow.execution.RequestContextHolder;


@Component
public class DocumentiFormValidator {
	
@Autowired
private RicercaRepository ricercaRepository;

public void validate(DocumentiForm documentiForm, ValidationContext context) {
		
		RequestContext rc = RequestContextHolder.getRequestContext();
		MessageContext messages = context.getMessageContext();
		
		Boolean check = false;
		if (context.getUserEvent().equals("salvaAll"))
			check=ricercaRepository.checkNomeDocumento(((MultipartFile)context.getUserValue("multipartFileUpload2")).getOriginalFilename(), ((SchedaCandidato)rc.getFlowScope().get("schedaCandidato")).getIdSchedaCandidato());
		else
			check=ricercaRepository.checkNomeDocumento(((MultipartFile)context.getUserValue("multipartFileUpload")).getOriginalFilename(), ((SchedaCandidato)rc.getFlowScope().get("schedaCandidato")).getIdSchedaCandidato());
		if(!check){		
    		messages.addMessage(new MessageBuilder().error().source("uploadDoc").defaultText("Documento non valido")
					.code("error.campo.nonvalido").build());
    	}		
				
	}
}
